package com.pms.util;


import com.alibaba.fastjson.JSONObject;
import com.pms.exception.R;
import com.pms.util.httpUtil.HttpClientUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * LBS 请求工具类
 * Created by Administrator on 2017/8/22.
 */
@Component
//@ConfigurationProperties(prefix="lbs.estateAgency")
@Configuration
public class LBSUtil {

    public void main(String arg[]) throws Exception {
//       System.out.print(poiCreate(104.045915,31.691608,"四川省成都市金牛区","棒棒鸡").toString());
//        System.out.print(poiUpdate("2295104071",null,null,null,null,null,"http://upimg.ahmkj.cn/updata/img38511708.png").toString());
        Map<String,Object> lbsParamMap = new HashMap<String,Object>();
        lbsParamMap.put("ak",getAK());
        lbsParamMap.put("geotable_id",getGeotableId());
        lbsParamMap.put("coord_type",3);
        lbsParamMap.put("longitude",104.045615);//经度
        lbsParamMap.put("latitude",31.691648);//纬度
        lbsParamMap.put("address","1213");//地址
        lbsParamMap.put("title","廖记棒棒鸡2号");//poi名称
        lbsParamMap.put("shop_signage","http://upimg.ahmkj.cn/updata/img31910225.png");//店铺主图
        lbsParamMap.put("class_id",898420965699117056L);//店铺分类
        JSONObject lbsJson = poiCreateByMap(lbsParamMap);
        System.out.println(lbsJson.toString());
//        System.out.println(createGeotable("estate_agency"));
    }

    /**
     * 百度LBS提供的AK值
     */
    @Value("${lbs.estateAgency.AK}")
    private String AK ;
    /**
     * LBS店铺表id
     */
    @Value("${lbs.estateAgency.geotableId}")
    private String geotableId;
    /**
     * 百度LBS创建数据请求
     */
    private static final String poiCreateUrl="http://api.map.baidu.com/geodata/v3/poi/create";
    /**
     * 百度LBS修改数据请求
     */
    private static final String poiUpdateUrl="http://api.map.baidu.com/geodata/v3/poi/update";
    /**
     * 百度LBS查询数据请求
     */
    private static final String poiSelectUrl="http://api.map.baidu.com/geodata/v3/poi/list";
    /**
     * 百度LBS周边搜索数据请求
     */
    private static final String poiGeoSearchUrl="http://api.map.baidu.com/geosearch/v3/nearby";
    /**
     * 百度LBS创建表  POST请求
     */
    private static final String createGeotableUrl="http://api.map.baidu.com/geodata/v3/geotable/create";
    /**
     * 百度LBS创建列  POST请求
     */
    private static final String createColumnUrl="http://api.map.baidu.com/geodata/v3/column/create";


    public String getAK() {
        return AK;
    }

    public void setAK(String AK) {
        this.AK = AK;
    }

    public String getGeotableId() {
        return geotableId;
    }

    public void setGeotableId(String shopGeotableId) {
        this.geotableId = shopGeotableId;
    }

    /**
     * 添加数据
     * @Param geotableId 表id
     * @Param longitude 经度
     * @Param latitude 纬度
     * @Param address 地址
     * @Param  title 名称(店铺名称)
     * @return
     */
    public JSONObject poiCreate(Double longitude,Double latitude,String address,String title,String shopSignage){
        JSONObject ResponseJSON = null;
        StringBuilder param = new StringBuilder("ak=").append(getAK()).append("&geotable_id=").append(getGeotableId()).append("&coord_type=3")
                .append("&latitude=").append(latitude).append("&longitude=").append(longitude).append("&state=1");

        if(StringUtils.isNotBlank(address)){
            param.append("&address=").append(address);
        }
        if(StringUtils.isNotBlank(title)){
            param.append("&title=").append(title);
        }
        if(StringUtils.isNotBlank(shopSignage)){
            param.append("&shop_signage=").append(shopSignage);
        }
        ResponseJSON =  HttpClientUtil.doPost(poiCreateUrl,param.toString());
        return ResponseJSON;
    }


    /**
     * 修改数据
     * @Param poiID POI数据id
     * @Param geotableId 表id
     * @Param longitude 经度
     * @Param latitude 纬度
     * @Param address 地址
     * @Param  title 名称(店铺名称)
     * @Param  state 店铺状态
     * @return
     */
    public JSONObject poiUpdate(String poiID,Double longitude,Double latitude,String address,String title,Integer state,String shopSignage){
        JSONObject ResponseJSON = null;
        StringBuilder param = new StringBuilder("ak=").append(getAK()).append("&geotable_id=").append(getGeotableId()).append("&id=").append(poiID);
        if(StringUtils.isNotBlank(address)){
            param.append("&address=").append(address);
        }
        if(StringUtils.isNotBlank(title)){
            param.append("&title=").append(title);
        }
        if(null!= latitude||null!=longitude){
            param.append("&coord_type=3");
        }
        if(null!= latitude) {
            param.append("&latitude=").append(latitude);
        }
        if(null!= longitude){
            param .append("&longitude=").append(longitude);
        }
        if(null!= state){
            param .append("&state=").append(state);
        }
        if(StringUtils.isNotBlank(shopSignage)){
            param.append("&shop_signage=").append(shopSignage);
        }
        ResponseJSON =  HttpClientUtil.doPost(poiUpdateUrl,param.toString());
        return ResponseJSON;
    }

    /**
     * 周边收缩店铺
     * @param longitude 经度值
     * @param latitude  纬度值
     * @param radius    搜索范围
     * @param pageNum   搜索页数
     * @param pageSize  搜索条数
     * @param filterStr 过滤条件( key:valeu|key:value 格式（以|区分）)
     * @param tags       搜索标签（ tag1 tag2 tag3 格式（以空格区分） ）
     * @param q           关键字（ 商品名称）
     * @return
     */
    public String poiGeoSearch(double longitude,double latitude,int radius,int pageNum,int pageSize,String filterStr,String tags,String sortBy,String q){
        String responseJSONstr = null;
        StringBuilder url = new StringBuilder(poiGeoSearchUrl).append("?ak=").append(getAK()).append("&geotable_id=").append(getGeotableId());
        url.append("&location=").append(longitude).append(",").append(latitude);
        url.append("&coord_type=").append(3).append("&radius=").append(radius);
        if(StringUtils.isNotBlank(tags)){
            url.append("&tags=").append(tags);
        }
        if(StringUtils.isNotBlank(sortBy)){
            url.append("&sortby=").append(sortBy);
        }
        if(StringUtils.isNotBlank(q)){
            url.append("&q=").append(q);
        }
        url.append("&page_index=").append(pageNum-1);
        url.append("&page_size=").append(pageSize);
        url.append("&filter=").append("state:2");//过滤（查询启用的店铺）
        if(StringUtils.isNotBlank(filterStr)){
            url.append("|").append(filterStr);
        }
        responseJSONstr =  HttpClientUtil.doGet(url.toString(),"");
        return responseJSONstr;
    }

    /**
     * 根据map生成请求参数字符串
     * @param paramMap
     * @return
     */
    public String getParamStr(Map<String, Object> paramMap){
        StringBuilder paramStr = new StringBuilder("");
        List<String> paramKeys = new ArrayList<String>(paramMap.size());
        paramKeys.addAll(paramMap.keySet());
        for (int x=0;x<paramKeys.size();x++){
            if(x==0){
                paramStr.append(paramKeys.get(x)).append("=").append(paramMap.get(paramKeys.get(x)));
            }
            if(x>0){
                paramStr.append("&").append(paramKeys.get(x)).append("=").append(paramMap.get(paramKeys.get(x)));
            }
        }
        return paramStr.toString();
    }

    /**
     *
     * @param paramMap
     * @return
     */
    public JSONObject poiUpdateByMap(Map<String, Object> paramMap){
        JSONObject ResponseJSON = null;
        ResponseJSON =  HttpClientUtil.doPost(poiUpdateUrl,getParamStr(paramMap));
        return ResponseJSON;
    }

    public JSONObject poiCreateByMap(Map<String, Object> paramMap){
        JSONObject ResponseJSON = null;
        ResponseJSON =  HttpClientUtil.doPost(poiCreateUrl,getParamStr(paramMap));
        return ResponseJSON;
    }

    /**
     * 查询数据详情
     * @param poiId
     * @return
     */
    public JSONObject poiDetDetailByPoiId(String poiId){
        StringBuilder url = new StringBuilder("http://api.map.baidu.com/geosearch/v3/detail/").append(poiId);
        url.append("?ak=").append(getAK()).append("&geotable_id=").append(getGeotableId()).append("&coord_type=").append(3);
        JSONObject ResponseJSON =  HttpClientUtil.doPost(url.toString(),"");
//        String status = ResponseJSON.getString("status");
        return ResponseJSON;
    }
    /**
     * LBS创建表
     * @Param geotablenName 表名
     * @Param geotype geotable表持有数据的类型(1-点(默认),3|面)
     * @return JSONObject{status:状态码(0成功),id:数据表id(geotable_id)} / null-geotablenName为空
     */
    public JSONObject createGeotable(String geotablenName){
        return createGeotable(geotablenName,null,null);
    }
    /**
     * LBS创建表
     * @Param geotablenName 表名
     * @Param geotype geotable表持有数据的类型(1-点(默认),3|面)
     * @Param isPublished 是否发布检索(1是，0否)
     * @return JSONObject{status:状态码(0成功),id:数据表id(geotable_id)} / null-geotablenName为空
     */
    public JSONObject createGeotable(String geotablenName,Integer geotype,Integer isPublished){
        if(StringUtils.isBlank(geotablenName)){return null;}
        if(null==isPublished||isPublished!=0){isPublished=1;}
        if(null==geotype||geotype!=3){geotype=1;}//默认表数据类型为 点
        JSONObject ResponseJSON = null;
        StringBuilder paramStr = new StringBuilder("ak=").append(getAK());
        paramStr.append("&name=").append(geotablenName);
        paramStr.append("&geotype=").append(geotype);
        paramStr.append("&is_published=").append(isPublished);
        ResponseJSON =  HttpClientUtil.doPost(createGeotableUrl,paramStr.toString());
        return ResponseJSON;
    }

    /**
     * LBS创建列
     * @Param columnNameDescription 列名描述
     * @Param columnName 列名
     * @Param columnType 列类型(1-int, 2-double, 3-string, 4-在线图片url)
     * @Param isSearchField 是否设置为 检索字段(1是|0否)(最多设置4个)
     * @Param isSortfilterField 是否设置为 排序字段(1是|0否)(最多设置15个)
     * @Param isIndexField 是否设置为 索引字段(1是|0否)(最多设置3个)
     * @Param geotableId 表id
     * @return JSONObject{status:状态码(0成功),id:列id} / null-参数不符合
     */
    public JSONObject createColumn(String geotableId,String columnNameDescription,String columnName
            ,int columnType,int isSearchField,int isIndexField,int isSortfilterField){
        if(StringUtils.isBlank(columnNameDescription)){return null;}
        if(StringUtils.isBlank(geotableId)){return null;}
        if(StringUtils.isBlank(columnName)){return null;}
        if(columnType<1||columnType>4){return null;}
        if(isSearchField!=0&&isSearchField!=1){return null;}
        if(isIndexField!=0&&isIndexField!=1){return null;}
        if(isSortfilterField!=0&&isSortfilterField!=1){return null;}
        JSONObject ResponseJSON = null;
        StringBuilder paramStr = new StringBuilder("ak=").append(getAK());
        paramStr.append("&geotable_id=").append(geotableId);
        paramStr.append("&name=").append(columnNameDescription);
        paramStr.append("&key=").append(columnName);
        paramStr.append("&type=").append(columnType);
        paramStr.append("&max_length=").append(2047);//默认最大长度
        paramStr.append("&is_search_field=").append(isSearchField);
        paramStr.append("&is_index_field=").append(isIndexField);
        paramStr.append("&is_sortfilter_field=").append(isSortfilterField);
        ResponseJSON =  HttpClientUtil.doPost(createColumnUrl,paramStr.toString());
        return ResponseJSON;
    }

    /**
     * LBS创建列
     * @Param geotableColumn LBSGeotableColumn
     * @return JSONObject{status:状态码(0成功),id:列id} / null-参数不符合
     */
    public JSONObject createColumn(LBSGeotableColumn geotableColumn){
        if(!geotableColumn.validateLBSGeotableColumn()){return null;}
        if(StringUtils.isBlank(getAK())&&StringUtils.isBlank(geotableColumn.getAk())){return null;}
        JSONObject ResponseJSON = null;
        StringBuilder paramStr = new StringBuilder("ak=");
        if(StringUtils.isNotBlank(getAK())){  paramStr.append(getAK());
        }else{   paramStr.append(geotableColumn.getAk()); }
        paramStr.append("&geotable_id=");
        if(StringUtils.isNotBlank(getGeotableId())){  paramStr.append(getGeotableId());
        }else{   paramStr.append( geotableColumn.getGeotableId() ); }
        paramStr.append("&name=").append(geotableColumn.getColumnNameDescription());
        paramStr.append("&key=").append(geotableColumn.getColumnName());
        paramStr.append("&type=").append(geotableColumn.getColumnType());
        if(geotableColumn.getColumnType()==3){
            paramStr.append("&max_length=").append(geotableColumn.getMaxLength());
            paramStr.append("&is_search_field=").append(geotableColumn.getIsSearchField());
        }
        if(geotableColumn.getColumnType()<3){
            paramStr.append("&is_sortfilter_field=").append(geotableColumn.getIsSortfilterField());
        }
        paramStr.append("&is_index_field=").append(geotableColumn.getIsIndexField());

        ResponseJSON =  HttpClientUtil.doPost(createColumnUrl,paramStr.toString());
        return ResponseJSON;
    }
    /**
     * LBS批量创建列
     * @Param geotableColumn LBSGeotableColumn
     * @return JSONObject{status:状态码(0成功),id:列id} / null-参数不符合
     */
    public List<JSONObject> createColumnList(List<LBSGeotableColumn> geotableColumnList){
        if(null==geotableColumnList||geotableColumnList.isEmpty()){return null;}
        List<JSONObject> jsonList  = new ArrayList<JSONObject>();
        for(int x=0;x<geotableColumnList.size();x++){
            JSONObject json = createColumn(geotableColumnList.get(x));
            jsonList.add(json);
        }
        return jsonList;
    }
}
